//
//  EDSMoLocationManager.m
//  DriveSchoolCoach
//
//  Created by TangBin on 2019/7/8.
//  Copyright © 2019 TangBin. All rights reserved.
//

#import "EDSMoLocationManager.h"
#import <UIKit/UIKit.h>

@implementation EDSMoLocationManager

+ (EDSMoLocationManager *)sharedGpsManager
{
    
    static EDSMoLocationManager *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[EDSMoLocationManager alloc] init];
    });
    return shared;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        // 打开定位 然后得到数据
        manager = [[CLLocationManager alloc] init];
        manager.delegate = self;
        //控制定位精度,越高耗电量越
        manager.desiredAccuracy = kCLLocationAccuracyBest;
        manager.distanceFilter = 100.0f;
        // 兼容iOS8.0版本
        /* Info.plist里面加上2项
         NSLocationAlwaysUsageDescription      Boolean YES
         NSLocationWhenInUseUsageDescription   Boolean YES
         */
        
        // 请求授权 requestWhenInUseAuthorization用在>=iOS8.0上
        // respondsToSelector: 前面manager是否有后面requestWhenInUseAuthorization方法
        // 1. 适配 动态适配
        if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)])
        {
            [manager requestWhenInUseAuthorization];
            [manager requestAlwaysAuthorization];
        }
        // 2. 另外一种适配 systemVersion 有可能是 8.1.1
        float osVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (osVersion >= 8)
        {
            [manager requestWhenInUseAuthorization];
            [manager requestAlwaysAuthorization];
//            manager.allowsBackgroundLocationUpdates = YES;
        }
        
    }
    return self;
}

- (void)getMoLocationWithSuccess:(MoLocationSuccess)success Failure:(MoLocationFailed)failure
{
    self.successCallBack = [success copy];
    self.failedCallBack = [failure copy];
    // 停止上一次的
    [manager stopUpdatingLocation];
    // 开始新的数据定位
//    [manager startMonitoringSignificantLocationChanges];
    [manager startUpdatingLocation];
}


+ (void)getMoLocationWithSuccess:(MoLocationSuccess)success Failure:(MoLocationFailed)failure
{
    [[EDSMoLocationManager sharedGpsManager] getMoLocationWithSuccess:success Failure:failure];
}


- (void)stop
{
    [manager stopUpdatingLocation];
}

+ (void)stop
{
    [[EDSMoLocationManager sharedGpsManager] stop];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    debugLog(@"didChangeAuthorizationStatus=%d", status);
    switch (status)
    {
        case kCLAuthorizationStatusNotDetermined:
            if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)])
            {
                [manager requestWhenInUseAuthorization];
            }
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse: // 当使用的时候允许
        {
            // 停止上一次的
            [manager stopUpdatingLocation];
            // 开始新的数据定位
            [manager startUpdatingLocation];
        } break;
        default:
            break;
    }
}

// 每隔一段时间就会调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    /*
    for (CLLocation *loc in locations)
    {
        CLLocationCoordinate2D l = loc.coordinate;
        double lat = l.latitude;
        double lnt = l.longitude;
        
        successCallBack ? successCallBack(lat, lnt) : nil;
    }*/
    __weak typeof(self)weakSelf = self;
    CLLocation *location = locations[0];
    CLLocationCoordinate2D coord = location.coordinate;
    double lat = coord.latitude;
    double lnt = coord.longitude;
    [self stop];
    EDSMoLocationModel *model = [EDSMoLocationModel new];
    model.lat = lat;
    model.lng = lnt;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error)
        {
            CLPlacemark *placemark = placemarks[0];
            
            model.country = placemark.country; // 国家
            model.province = placemark.administrativeArea; // 省
            model.city = placemark.locality; // 市
//            NSString *street = placemark.thoroughfare; // 路
            model.area = placemark.subLocality; // 区
//            debugLog(@"pl=%@", [placemark modelToJSONString]);
            weakSelf.successCallBack ? weakSelf.successCallBack(model) : nil;
        }
        else
        {
            weakSelf.successCallBack ? weakSelf.successCallBack(model) : nil;
        }
    }];
    
}

//失败代理方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    self.failedCallBack ? self.failedCallBack(error) : nil;
    if ([error code] == kCLErrorDenied)
    {
        debugLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown)
    {
        debugLog(@"无法获取位置信息");
    }
    debugLog(@"tb-error=%@", [error localizedDescription]);
}


@end
